package com.zbx.springcloud.controller;

import com.netflix.discovery.DiscoveryClient;
import com.zbx.springcloud.pojo.Dept;
import com.zbx.springcloud.service.DeptClientService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: zbxComputer
 * @time: 2023/5/23 21:12
 */


@RestController
@RequestMapping("/consumer/dept")
public class DeptConsumerController {
    //spring提供了 restful 方式的 restTemplate 类 但是要自己配置
    @Resource
    private RestTemplate restTemplate;//提供多种便捷访问 远程http服务的方法 是一种简单的restful服务模板


    //通过Feign实现面向接口式的访问
    @Resource
    private DeptClientService clientService;

    //private final static String URL_PREFIX = "http://127.0.0.1:8001";
    //使用负载均衡后 服务注册中心地址应该是变量 通过服务名来访问 http://SPRINGCLOUD-PROVIDER-DEPT
    private final static String URL_PREFIX = "http://DEPT-PROVIDER/";


    @RequestMapping("/get/{id}")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = null;
        try {
            dept = clientService.queryById(id);
            //dept = restTemplate.getForObject(URL_PREFIX + "dept/get/" + id, Dept.class);
        } catch (Exception e) {
            throw new RuntimeException("降级啦");
        }
//        Dept dept1 = clientService.queryById(id);
        return dept;
    }

    @RequestMapping("/add")
    public Dept add(Dept dept) {
        //restTemplate.postForObject(URL_PREFIX + "dept/add", dept, Boolean.class)
        if (ObjectUtils.isEmpty(dept)) {
            throw new RuntimeException("降级");
        }
        Dept d = clientService.addDept(dept);
        return d;
    }

    @RequestMapping("/list")
    public List<Dept> list() {
        return clientService.queryALL();
        // return restTemplate.getForObject(URL_PREFIX + "dept/list", List.class);
    }
}
